package com.feihua.starter.web.modules.hdb.mvc;

import com.feihua.framework.rest.ResponseJsonRender;
import com.feihua.framework.rest.interceptor.RepeatFormValidator;
import com.feihua.framework.rest.modules.common.mvc.BaseController;
import com.feihua.starter.service.api.ApiHdbMsgPoService;
import com.feihua.starter.service.modules.hdb.dto.HdbMsgDto;
import com.feihua.starter.service.modules.hdb.dto.SearchHdbMsgsConditionDto;
import com.feihua.starter.service.modules.hdb.po.HdbMsgPo;
import com.feihua.utils.http.httpServletResponse.ResponseCode;
import feihua.jdbc.api.pojo.BasePo;
import feihua.jdbc.api.pojo.PageAndOrderbyParamDto;
import feihua.jdbc.api.pojo.PageResultDto;
import feihua.jdbc.api.utils.OrderbyUtils;
import feihua.jdbc.api.utils.PageUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * 活动吧消息管理
 * Created by revolver
 */
@RestController
@RequestMapping("/hdb")
public class HdbMsgController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(HdbMsgController.class);

    @Autowired
    private ApiHdbMsgPoService apiHdbMsgPoService;

    /**
     * 单资源，添加
     *
     * @param hdbMsgDto
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:msg:add")
    @RequestMapping(value = "/msg", method = RequestMethod.POST)
    public ResponseEntity add(HdbMsgDto hdbMsgDto) {
        logger.info("添加活动吧消息开始");
        logger.info("当前登录用户id:{}", getLoginUser().getId());
        ResponseJsonRender resultData = new ResponseJsonRender();
        // 表单值设置
        HdbMsgPo basePo = new HdbMsgPo();
        BeanUtils.copyProperties(hdbMsgDto, basePo);

        apiHdbMsgPoService.preInsert(basePo, getLoginUser().getId());
        HdbMsgDto r = apiHdbMsgPoService.insert(basePo);
        if (r == null) {
            // 添加失败
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            logger.info("code:{},msg:{}", resultData.getCode(), resultData.getMsg());
            logger.info("添加活动吧消息结束，失败");
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        } else {
            // 添加成功，返回添加的数据
            resultData.setData(r);
            logger.info("添加活动吧消息id:{}", r.getId());
            logger.info("添加活动吧消息结束，成功");
            return new ResponseEntity(resultData, HttpStatus.CREATED);
        }
    }

    /**
     * 单资源，删除
     *
     * @param id
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:msg:delete")
    @RequestMapping(value = "/msg/{id}", method = RequestMethod.DELETE)
    public ResponseEntity delete(@PathVariable String id) {
        logger.info("删除活动吧消息开始");
        logger.info("用户id:{}", getLoginUser().getId());
        logger.info("活动吧消息id:{}", id);
        ResponseJsonRender resultData = new ResponseJsonRender();

        int r = apiHdbMsgPoService.deleteFlagByPrimaryKeyWithUpdateUser(id, getLoginUser().getId());
        if (r <= 0) {
            // 删除失败，可能没有找到资源
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            logger.info("code:{},msg:{}", resultData.getCode(), resultData.getMsg());
            logger.info("删除活动吧消息结束，失败");
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        } else {
            // 删除成功
            logger.info("删除的活动吧消息id:{}", id);
            logger.info("删除活动吧消息结束，成功");
            return new ResponseEntity(resultData, HttpStatus.NO_CONTENT);
        }
    }

    /**
     * 单资源，用户未读消息
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:msg:read")
    @RequestMapping(value = "/msg/read/{read}", method = RequestMethod.GET)
    public ResponseEntity read(@PathVariable String read) {
        logger.info("获取用户未读消息开始");
        logger.info("用户id:{}", getLoginUser().getId());
        logger.info("活动吧消息read:{}", read);
        ResponseJsonRender resultData = new ResponseJsonRender();
        HdbMsgPo entity = new HdbMsgPo();
        entity.setDelFlag(BasePo.YesNo.N.name());
        entity.setReadFlag(read);
        entity.setUserId(getLoginUserId());
        final int count = apiHdbMsgPoService.count(entity);
        resultData.setData(count);
        logger.info("获取用户未读消息数:{}", count);
        logger.info("获取用户未读消息结束，成功");
        return new ResponseEntity(resultData, HttpStatus.OK);
    }


    /**
     * 单资源，用户更新未读消息为已读
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:msg:read")
    @RequestMapping(value = "/msg/read", method = RequestMethod.PUT)
    public ResponseEntity read() {
        logger.info("用户更新未读消息为已读开始");
        logger.info("用户id:{}", getLoginUser().getId());
        ResponseJsonRender resultData = new ResponseJsonRender();
        HdbMsgPo entity = new HdbMsgPo();
        entity.setReadFlag(BasePo.YesNo.Y.name());
        HdbMsgPo condition = new HdbMsgPo();
        condition.setReadFlag(BasePo.YesNo.N.name());
        condition.setUserId(getLoginUserId());
        apiHdbMsgPoService.preUpdate(entity, getLoginUserId());
        final int r = apiHdbMsgPoService.updateSelective(entity, condition);
        if (r <= 0) {
            // 更新未读消息失败，可能没有找到资源
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            logger.info("code:{},msg:{}", resultData.getCode(), resultData.getMsg());
            logger.info("用户更新未读消息为已读结束，失败");
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        } else {
            // 更新未读消息成功
            logger.info("更新未读消息数:{}", r);
            logger.info("用户更新未读消息为已读结束，成功");
            return new ResponseEntity(resultData, HttpStatus.NO_CONTENT);
        }
    }

    /**
     * 复数资源，搜索活动吧消息
     *
     * @param dto
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:msg:search")
    @RequestMapping(value = "/msgs", method = RequestMethod.GET)
    public ResponseEntity search(SearchHdbMsgsConditionDto dto) {
        ResponseJsonRender resultData = new ResponseJsonRender();
        PageAndOrderbyParamDto pageAndOrderbyParamDto = new PageAndOrderbyParamDto(PageUtils.getPageFromThreadLocal(), OrderbyUtils.getOrderbyFromThreadLocal());
        // 设置当前登录用户id
        PageResultDto<HdbMsgDto> list = apiHdbMsgPoService.searchHdbMsgsDsf(dto, pageAndOrderbyParamDto);

        if (CollectionUtils.isNotEmpty(list.getData())) {
            resultData.setData(list.getData());
            resultData.setPage(list.getPage());
            return new ResponseEntity(resultData, HttpStatus.OK);
        } else {
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        }
    }
}
